package henu.action;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.net.ssl.HttpsURLConnection;
import javax.servlet.http.HttpSession;

import oracle.net.aso.s;

import org.apache.struts2.ServletActionContext;

import net.sf.json.JSONObject;
import henu.bean.Exam;
import henu.bean.Exercise;
import henu.bean.Exercise_Front;
import henu.bean.ManagePerson;
import henu.bean.PInformation;
import henu.bean.Questions;
import henu.dao.ExamDao;
import henu.dao.ExerciseDao;
import henu.dao.QuestionsDao;
import henu.dao.factory.DaoFactory;
import henu.service.RandomList;
import henu.util.AJAX;
import henu.util.CONSTANTS;
import henu.util.Page;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class ExerciseAction extends ActionSupport {
	private String args;
	private String args0;
	private Exercise exercise;

	private String[] answerarray;
	private String totalques;
	public static final String QUES_LIST = "queslist"; // 用来表示session中考题的名称
	public static final String TEST_SCORE = "testscore"; // 用来表示session中考题的名称
	public static final String ANSWER_ARRAY = "ANSWER_ARRAY"; // 用来表示session中考题的名称
	public static final String CURRENT_EXAM = "CURRENT_EXAM"; // 用来表示session中考题的名称
	private AJAX ajax = new AJAX();
	// 分页排序
	private Page page = new Page();
	private int pageNum = 1;
	private int numPerPage = 10;
	private String orderField = "eid";
	private String orderDirection = "asc";
	// 检索
	private String property = "-1";
	private String key = "-1";
	
	//dao 
	private HttpSession session  ;
	private ExerciseDao exerdao ; 
	private String url;
	private Exam exam;
	private List<Questions> queslist;
	private List<PInformation> user_list;
	private List<Exercise_Front> exer_list;
	private List<Exam> list;
	private Map<String, String> examsubmap;
	private String result;
	private JSONObject jsonob; // 定义的json对象，用来传输接送相关的信息

	public List<Exercise_Front> getExer_list() {
		return exer_list;
	}

	public void setExer_list(List<Exercise_Front> exer_list) {
		this.exer_list = exer_list;
	}

	public Exercise getExercise() {
		return exercise;
	}

	public List<PInformation> getUser_list() {
		return user_list;
	}

	public void setUser_list(List<PInformation> user_list) {
		this.user_list = user_list;
	}

	public void setExercise(Exercise exercise) {
		this.exercise = exercise;
	}

	public String getArgs0() {
		return args0;
	}

	public void setArgs0(String args0) {
		this.args0 = args0;
	}

	public String[] getAnswerarray() {
		return answerarray;
	}

	public void setAnswerarray(String[] answerarray) {
		this.answerarray = answerarray;
	}

	public String getArgs() {
		return args;
	}

	public String getTotalques() {
		return totalques;
	}

	public void setTotalques(String totalques) {
		this.totalques = totalques;
	}

	public void setArgs(String args) {
		this.args = args;
	}

	public AJAX getAjax() {
		return ajax;
	}

	public void setAjax(AJAX ajax) {
		this.ajax = ajax;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public Exam getExam() {
		return exam;
	}

	public void setExam(Exam exam) {
		this.exam = exam;
	}

	public List<Questions> getQueslist() {
		return queslist;
	}

	public void setQueslist(List<Questions> queslist) {
		this.queslist = queslist;
	}

	public List<Exam> getList() {
		return list;
	}

	public void setList(List<Exam> list) {
		this.list = list;
	}

	public Map<String, String> getExamsubmap() {
		return examsubmap;
	}

	public void setExamsubmap(Map<String, String> examsubmap) {
		this.examsubmap = examsubmap;
	}

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	public JSONObject getJsonob() {
		return jsonob;
	}

	public void setJsonob(JSONObject jsonob) {
		this.jsonob = jsonob;
	}

	public Page getPage() {
		return page;
	}

	public void setPage(Page page) {
		this.page = page;
	}

	public int getPageNum() {
		return pageNum;
	}

	public void setPageNum(int pageNum) {
		this.pageNum = pageNum;
	}

	public int getNumPerPage() {
		return numPerPage;
	}

	public void setNumPerPage(int numPerPage) {
		this.numPerPage = numPerPage;
	}

	public String getOrderField() {
		return orderField;
	}

	public void setOrderField(String orderField) {
		this.orderField = orderField;
	}

	public String getOrderDirection() {
		return orderDirection;
	}

	public void setOrderDirection(String orderDirection) {
		this.orderDirection = orderDirection;
	}

	public String getProperty() {
		return property;
	}

	public void setProperty(String property) {
		this.property = property;
	}

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	/**
	 * 学生进来考试先把试题准备好 准备好之后就可以开始考试了 开始把前台的那套东西弄过来
	 * */
	/**
	 * 显示所有的考试列表
	 * */
	public String all() {
		// System.out.println("访问到all方法");
		if (orderField.equals("") || orderDirection.equals("")) {
			orderField = "eid";
			orderDirection = "asc";
		}
		if (property.equals("") || key.equals("")) {
			property = "-1";
			key = "－1";
		}
		// System.out.println("action查询的关键字是:" + key);
		// System.out.println("查询的依据:" + property);
		page.setProperties("Exam", pageNum, numPerPage, property, key);
		// 给page这个class设置属性
		list = DaoFactory.getExamDaoInstance().findByProperty(property.trim(),
				key.trim(), orderField.trim(), orderDirection.trim(),
				page.getStart(), page.getEnd());
		url = "/front/exerciseManage.jsp";
		return SUCCESS;
	}

	/**
	 * 这个方法应该作为学生考试的入口
	 * */
	public String begin() {
		HttpSession session = ServletActionContext.getRequest().getSession();
		RandomList rl = new RandomList();
		QuestionsDao quesdao = DaoFactory.getQuesttionDaoInstance();
		ExamDao edao = DaoFactory.getExamDaoInstance();
		List<Questions> questemplist = new ArrayList<Questions>(); // 临时容器
		queslist = new ArrayList<Questions>();
		exam = edao.findById(Integer.parseInt(args));
		session.setAttribute(CURRENT_EXAM, exam); // 方便计算分数记录成绩的时候 读取信息
		totalques = (Integer.parseInt(exam.getJudgecount()) + Integer
				.parseInt(exam.getSelectcount())) + "";
		answerarray = new String[Integer.parseInt(totalques)]; // 把存储答案数组初始化
		session.setAttribute(ANSWER_ARRAY, answerarray); // 把答案数组放到session中
		// System.out.println("试卷的题目数量:"+totalques);
		// System.out.println("本次考试的时常："+exam.getDuration());
		// 首先要知道开始的是那一场考试，根据这一场考试的信息来出题
		String examtype = exam.getExamtype(); // 首先判断是什么类型的考试
		// System.out.println("考试的类型:"+examtype);
		String selectcount = exam.getSelectcount(); // 选择题的数量
		String judgecount = exam.getJudgecount(); // 判断题的数量
		Set<Integer> quesset = null;
		if (examtype.equals("0")) { // 专题考试
			String subject = exam.getSubject(); // 获取专题名字
			questemplist = quesdao.status("subject", subject, "type", "选择题"); // 选择题
			// 拿到了所有的选择题，根据题目的数量随机出题
			// System.out.println("第一次："+questemplist.size());
			quesset = rl.randomNum(questemplist.size(),
					Integer.parseInt(selectcount));
			for (int i : quesset) {
				queslist.add(questemplist.get(i)); // 放在新的容器中
			}
			questemplist.clear(); // 清空容器来节省内存
			// 这个返回的set集合里面放的都是数字 可以遍历出来，再申请一个list
			questemplist = quesdao.status("subject", subject, "type", "判断题"); // 判断题
			quesset.clear();// 清空集合重新生成
			quesset = rl.randomNum(questemplist.size(),
					Integer.parseInt(judgecount));
			for (int i : quesset) {
				queslist.add(questemplist.get(i)); // 放在新的容器中
			}
		} else {
			questemplist = quesdao.findAll("qid", "asc", "type", "选择题"); // 选择题
			quesset = rl.randomNum(questemplist.size(),Integer.parseInt(selectcount)); //假如size 是10最大生成的数字是9不会越界
			queslist = new ArrayList<Questions>();
			
			for (int i : quesset) {
				queslist.add(questemplist.get(i)); // 放在新的容器中
			}
			// 这个返回的set集合里面放的都是数字 可以遍历出来，再申请一个list
			questemplist = quesdao.findAll("qid", "asc", "type", "判断题"); // 判断题
			quesset.clear();// 清空集合重新生成
			quesset = rl.randomNum(questemplist.size(),
					Integer.parseInt(judgecount));
			for (int i : quesset) {
				queslist.add(questemplist.get(i)); // 放在新的容器中
			}
		}
		// 所有需要的试题都放在queslist放到session中
		session.setAttribute(QUES_LIST, queslist);
		url = "/front/exam.jsp";
		return SUCCESS;
	}

	/**
	 * 切换到下一题目
	 * */
	public String next() {
		// System.out.println("题目的索引："+args);
		HttpSession session = ServletActionContext.getRequest().getSession();
		queslist = (List<Questions>) session.getAttribute(QUES_LIST);
		// System.out.println("题目的数量："+queslist.size());
		Questions q = queslist.get(Integer.parseInt(args));
		// 防止意外透漏答案此处讲答案过滤掉
		// q.setAnswer("NULL");
		// System.out.println(e.getAnswer());
		jsonob = new JSONObject().fromObject(q);
		result = jsonob.toString();
		return SUCCESS;
	}

	/**
	 * 切换到上一题目 与切换到下一题唯一不同的就是这个需要把答案也传输过去，是学生做的答案
	 * */
	public String pre() {
		// System.out.println("访问到上一题目："+args);
		HttpSession session = ServletActionContext.getRequest().getSession();
		queslist = (List<Questions>) session.getAttribute(QUES_LIST);
		answerarray = (String[]) session.getAttribute(ANSWER_ARRAY);
		Questions q = queslist.get(Integer.parseInt(args));
		// 此处要把学生做的答案封装进来
		// 防止意外透漏答案此处讲答案过滤掉
		/**
		 * 这个地方还要读取到学生做的题目的答案 所有的判断题答案只有0和 1 没有 true 和false
		 * */
		q.setAnswer(answerarray[Integer.parseInt(args)]);
		// System.out.println(e.getAnswer());
		jsonob = new JSONObject().fromObject(q);
		result = jsonob.toString();
		// System.out.println("上一题目的答案:"+q.getAnswer());
		return SUCCESS;
	}

	/**
	 * 存储学生做的答案
	 * */
	public String rec() {
		// 每次做题都去后台一次去session中把这个数组变量拿出来，然后给其赋值
		HttpSession session = ServletActionContext.getRequest().getSession();
		answerarray = (String[]) session.getAttribute(ANSWER_ARRAY);
		// System.out.println("记录索引："+args);
		// System.out.println("记录答案："+args0);
		answerarray[Integer.parseInt(args)] = args0;
		return SUCCESS;
	}

	/**
	 * 计算分数，把成绩录入数据库
	 * */
	public String compu() {
		session = ServletActionContext.getRequest().getSession();
		PInformation currentuser = (PInformation) session
				.getAttribute(CONSTANTS.SESSION_PERSON); // 获取到后台登录的用户
		String idcard = currentuser.getIdCard();
		exam = (Exam) session.getAttribute(CURRENT_EXAM);
		exerdao = DaoFactory.getExerciseDaoInstance();
		exerdao.delScore(exam.getEid(), idcard);
		/*
		 * 给考生更新成绩之前先把他之前考试的成绩删除
		 */
		Questions questemp = null;
		int selectscore = exam.getSelectscore(); // 选择题的分数
		int judgescore = exam.getJudgescore(); // 判断题的分数
		answerarray = (String[]) session.getAttribute(ANSWER_ARRAY); // 获取用户的答案
		queslist = (List<Questions>) session.getAttribute(QUES_LIST);
		
		//System.out.println("身份证号码:" + idcard);
		exercise = new Exercise();
		exercise.setEid(exam.getEid());
		exercise.setIdcard(idcard);
		for (int i = 0; i < answerarray.length; i++) {
			// System.out.println("学生的答案:"+answerarray[i]);
			questemp = queslist.get(i);
			exercise.setQid(questemp.getQid());
			// System.out.println("正确答案:"+questemp.getAnswer());
			// 此处应该直接把学生考试的所有题目的记录写进数据库里面
			if (questemp.getAnswer().equals(answerarray[i])) { // 如果答案相同
				args0 = questemp.getType();
				if (args0.equals("选择题")) {
					exercise.setScore(selectscore);
				} else if (args0.equals("判断题")) {
					exercise.setScore(judgescore);
				}
			} else {
				exercise.setScore(0); // 题目做错就是0分
			}
			// 设置完成之后写入数据库
			exerdao.save(exercise);
		}
		args0 = String.valueOf(exerdao.sumScore(idcard, exam.getEid()));
		session.setAttribute("TESTSCORE", args0);
		ajax = new AJAX();
		ajax.setCallbackType("forward");
		ajax.setForwardUrl("/aqjy/front/examResult.jsp");
		ajax.setStatusCode("200");
		// 前台接受一个testScore的参数 ，还需要有一个可以从数据库统计分数的方法，哪一场考试，谁两个参数
		url = "/admin/ajax.jsp";
		return SUCCESS;
	}
	/**
	 * 查看一场考试的成绩
	 * 加入用户没
	 * */
	public String score() {
		HttpSession session = ServletActionContext.getRequest().getSession();
		// 只需要传来一个考场的参数就ok了
		ExerciseDao exerdao = DaoFactory.getExerciseDaoInstance();
		PInformation person = (PInformation) session
				.getAttribute(CONSTANTS.SESSION_PERSON);
		args0 = String.valueOf(exerdao.sumScore(person.getIdCard(),
				Integer.parseInt(args)));
		session.setAttribute("TESTSCORE", args0);
		url = "/front/examResult.jsp";
		return SUCCESS;
	}
	/**
	 * 成绩统计 ，按照每次考试的做一个成绩统计
	 * */
	public String statistics() { // 这个方法用来统计及格与不及格的人生，以及各个 分数阶段的学生所占的百分比
		int[] stage = new int[5];
		stage = DaoFactory.getExerciseDaoInstance().tongji(
				Integer.parseInt(args));
		int totalpeople = 0; // 总人数
		int passstu = 0; // 及格的人数
		// 所有的人数，以及及格的人数
		for (int i = 0; i < stage.length; i++) {
			totalpeople += stage[i];
		}
		passstu = totalpeople - stage[0];
		HttpSession session = ServletActionContext.getRequest().getSession();
		session.setAttribute("stage", stage);
		session.setAttribute("passstu", passstu);
		url = "/admin/chart/test/exam_chart.jsp";
		return SUCCESS;
	}

}
